﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySQL.Db;
using MySql.Data.MySqlClient;
using System.Threading;
using System.Threading.Tasks;

namespace Gollie.Ajax
{
	public class FinalizePendingPayment : AjaxResult
	{
		public FinalizePendingPayment() : base(null) {}

		public FinalizePendingPayment(AjaxArg arg)
			: base(arg)
		{
		}

		protected override void Init(AjaxArg ajaxArg)
		{
			FinalizePendingPaymentArg arg = (FinalizePendingPaymentArg)ajaxArg;

			try
			{
				uint customerId = Convert.ToUInt32(arg.tokenUser);
				uint vendorId = Convert.ToUInt32(arg.vendorId);
				ushort action = Convert.ToUInt16(arg.action);
				string email = arg.email;

				string pw = Hash.GetHash(arg.pinCode);

				logger.Info("Finalizing pending payment...cust:{0}, vendor {1}, action {2}", customerId, vendorId, action);
				ResultSet r = Database.Queries.FinalizePendingPayment(vendorId, customerId, arg.verificationCode, pw, action);

				if (action == 1 && r.Count == 1)
				{
					decimal amount = r.GetDecimal(0, "amount");

					logger.Info("Finalized pending payment: € {0}", amount);

					if (email == "1")
					{
						Task.Run(() => {
							int cashierId = r.GetInt32(0, "cashierid");
						
							UserInfo customerInfo = Database.Queries.GetUser((int)customerId, true);
							UserInfo cashierInfo = Database.Queries.GetUser(cashierId, true);

							WebMethods.SendConfirmationMail(customerInfo, cashierInfo, amount, DateTime.Now);
						});
					}
				}
			}
			catch (MySqlException mySqlEx)
			{
				this.ErrorCode = mySqlEx.Number;
				this.ErrorMessage = MySqlErrorCodes.GetInstance().GetMessage(mySqlEx);
				logger.Warn("FinalizePendingPayment failed for userid {0}: {1}", arg.tokenUser, this.ErrorMessage);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
				logger.Warn("FinzlizePendingPayment failed for userid {0}: {1}", arg.tokenUser, this.ErrorMessage);
			}
		}
	}
}